{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "fde98ddf",
   "metadata": {},
   "source": [
    "# Creating a basic chat experience with kernel arguments\n",
    "\n",
    "In this example, we show how you can build a simple chat bot by sending and updating the kernel arguments with your requests.\n",
    "\n",
    "We introduce the Kernel Arguments object which in this demo functions similarly as a key-value store that you can use when running the kernel.\n",
    "\n",
    "The chat history is local (i.e. in your computer's RAM) and not persisted anywhere beyond the life of this Jupyter session.\n",
    "\n",
    "In future examples, we will show how to persist the chat history on disk so that you can bring it into your applications.\n",
    "\n",
    "In this chat scenario, as the user talks back and forth with the bot, the chat context gets populated with the history of the conversation. During each new run of the kernel, the kernel arguments and chat history can provide the AI with its variables' content.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "92f69b34",
   "metadata": {},
   "outputs": [],
   "source": [
    "!python -m pip install semantic-kernel==0.9.7b1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a235b31",
   "metadata": {},
   "outputs": [],
   "source": [
    "from services import Service\n",
    "\n",
    "# Select a service to use for this notebook (available services: OpenAI, AzureOpenAI, HuggingFace)\n",
    "selectedService = Service.OpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68301108",
   "metadata": {},
   "outputs": [],
   "source": [
    "from semantic_kernel import Kernel\n",
    "\n",
    "kernel = Kernel()\n",
    "\n",
    "service_id = None\n",
    "if selectedService == Service.OpenAI:\n",
    "    from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion\n",
    "    from semantic_kernel.utils.settings import openai_settings_from_dot_env\n",
    "\n",
    "    api_key, org_id = openai_settings_from_dot_env()\n",
    "    service_id = \"oai_chat_gpt\"\n",
    "    kernel.add_service(\n",
    "        OpenAIChatCompletion(service_id=service_id, ai_model_id=\"gpt-3.5-turbo-1106\", api_key=api_key, org_id=org_id),\n",
    "    )\n",
    "elif selectedService == Service.AzureOpenAI:\n",
    "    from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion\n",
    "    from semantic_kernel.utils.settings import azure_openai_settings_from_dot_env\n",
    "\n",
    "    deployment, api_key, endpoint = azure_openai_settings_from_dot_env()\n",
    "    service_id = \"aoai_chat_completion\"\n",
    "    kernel.add_service(\n",
    "        AzureChatCompletion(service_id=service_id, deployment_name=deployment, endpoint=endpoint, api_key=api_key),\n",
    "    )"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "7971783d",
   "metadata": {},
   "source": [
    "Let's define a prompt outlining a dialogue chat bot.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e84a05fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt = \"\"\"\n",
    "ChatBot can have a conversation with you about any topic.\n",
    "It can give explicit instructions or say 'I don't know' if it does not have an answer.\n",
    "\n",
    "{{$history}}\n",
    "User: {{$user_input}}\n",
    "ChatBot: \"\"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "61716b16",
   "metadata": {},
   "source": [
    "Register your semantic function\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a3e4b160",
   "metadata": {},
   "outputs": [],
   "source": [
    "from semantic_kernel.connectors.ai.open_ai.prompt_execution_settings.open_ai_prompt_execution_settings import (\n",
    "    OpenAIChatPromptExecutionSettings,\n",
    ")\n",
    "from semantic_kernel.prompt_template.input_variable import InputVariable\n",
    "from semantic_kernel.prompt_template import PromptTemplateConfig\n",
    "\n",
    "if selectedService == Service.OpenAI:\n",
    "    execution_settings = OpenAIChatPromptExecutionSettings(\n",
    "        service_id=service_id,\n",
    "        ai_model_id=\"gpt-3.5-turbo-1106\",\n",
    "        max_tokens=2000,\n",
    "        temperature=0.7,\n",
    "    )\n",
    "elif selectedService == Service.AzureOpenAI:\n",
    "    execution_settings = OpenAIChatPromptExecutionSettings(\n",
    "        service_id=service_id,\n",
    "        ai_model_id=deployment,\n",
    "        max_tokens=2000,\n",
    "        temperature=0.7,\n",
    "    )\n",
    "\n",
    "prompt_template_config = PromptTemplateConfig(\n",
    "    template=prompt,\n",
    "    name=\"chat\",\n",
    "    template_format=\"semantic-kernel\",\n",
    "    input_variables=[\n",
    "        InputVariable(name=\"user_input\", description=\"The user input\", is_required=True),\n",
    "        InputVariable(name=\"history\", description=\"The conversation history\", is_required=True),\n",
    "    ],\n",
    "    execution_settings=execution_settings,\n",
    ")\n",
    "\n",
    "chat_function = kernel.add_function(\n",
    "    function_name=\"chat\",\n",
    "    plugin_name=\"chatPlugin\",\n",
    "    prompt_template_config=prompt_template_config,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6a0f7c01",
   "metadata": {},
   "outputs": [],
   "source": [
    "from semantic_kernel.contents import ChatHistory\n",
    "\n",
    "chat_history = ChatHistory()\n",
    "chat_history.add_system_message(\"You are a helpful chatbot who is good about giving book recommendations.\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "6e8a676f",
   "metadata": {},
   "source": [
    "Initialize the Kernel Arguments\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a4be7394",
   "metadata": {},
   "outputs": [],
   "source": [
    "from semantic_kernel.functions import KernelArguments\n",
    "\n",
    "arguments = KernelArguments(user_input=\"Hi, I'm looking for book suggestions\", history=chat_history)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4ce7c497",
   "metadata": {},
   "source": [
    "Chat with the Bot\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ec41eb8",
   "metadata": {},
   "outputs": [],
   "source": [
    "response = await kernel.invoke(chat_function, arguments)\n",
    "print(response)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "a5b03748",
   "metadata": {},
   "source": [
    "Update the history with the output\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f50f517d",
   "metadata": {},
   "outputs": [],
   "source": [
    "chat_history.add_assistant_message(str(response))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "23a2eb02",
   "metadata": {},
   "source": [
    "Keep Chatting!\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c59efe45",
   "metadata": {},
   "outputs": [],
   "source": [
    "async def chat(input_text: str) -> None:\n",
    "    # Save new message in the context variables\n",
    "    print(f\"User: {input_text}\")\n",
    "\n",
    "    # Process the user message and get an answer\n",
    "    answer = await kernel.invoke(chat_function, KernelArguments(user_input=input_text, history=chat_history))\n",
    "\n",
    "    # Show the response\n",
    "    print(f\"ChatBot: {answer}\")\n",
    "\n",
    "    chat_history.add_user_message(input_text)\n",
    "    chat_history.add_assistant_message(str(answer))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "06ee244e",
   "metadata": {},
   "outputs": [],
   "source": [
    "await chat(\"I love history and philosophy, I'd like to learn something new about Greece, any suggestion?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82be4e7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "await chat(\"that sounds interesting, what is it about?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82fe0139",
   "metadata": {},
   "outputs": [],
   "source": [
    "await chat(\"if I read that book, what exactly will I learn about Greek history?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55b3a9f2",
   "metadata": {},
   "outputs": [],
   "source": [
    "await chat(\"could you list some more books I could read about this topic?\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c30bac97",
   "metadata": {},
   "source": [
    "After chatting for a while, we have built a growing history, which we are attaching to each prompt and which contains the full conversation. Let's take a look!\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e34ae55",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(chat_history)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
